//
//  HomeTableViewController.swift
//  WBDemo
//
//  Created by Jin on 16/04/2018.
//  Copyright © 2018 com.baidu.123. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh

class HomeTableViewController: BaseTableViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //检测登录
        if !login {
            visitorView?.setupVisitorInfo(imageName: nil, title: "关注一些人,回这里看看有什么惊喜!")
            return
        }
      
        //初始化导航条
        setupNav()
        
        //注册监听
        NotificationCenter.default.addObserver(self, selector: #selector(titleBtnChange), name: NSNotification.Name(rawValue: JLPopoverViewControllerShowClick), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(titleBtnChange), name: NSNotification.Name(rawValue: JLPopoverViewControllerDismissClick), object: nil)
        
        //发送网络请求
        //loadstatuses(false)
        
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200
        
        //刷新数据
        setUpHeaderView()
        setUpFooterView()
        /*
        //简单的下拉刷新实现
        refreshControl = UIRefreshControl(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        refreshControl?.tintColor = UIColor.orange
        refreshControl?.attributedTitle = NSAttributedString(string: "下拉刷新")
        refreshControl?.addTarget(self, action: #selector(downRefresh), for:.valueChanged)
        */
        
        //添加提示label
        setupTipLabel()
        
    }
    
    // MARK: - 懒加载
    //保存模型数组
    private lazy var statusesArray : [HomeViewModel] = [HomeViewModel]()
    //提示label
    private lazy var tipLabel : UILabel = UILabel()
    
    private lazy var titleButton:TitleButton = {
        let titleButton = TitleButton()
        titleButton.addTarget(self, action: #selector(titleBtnClick), for: .touchUpInside)
        return titleButton
    }()
    
    private lazy var popoverManager:PopoverAnimationManager = {
        let popoverManager = PopoverAnimationManager(presentedViewController: self, presenting: nil)
        popoverManager.presentedFrame = CGRect(x: 100, y: 56, width: 200, height: 200)
        return popoverManager
    }()
    
    // MARK: - 内部控制方法
    @objc private func downRefresh(){
        loadstatuses(true)
    }
    
    @objc private func upRefresh(){
        loadstatuses(false)
    }
    
    @objc private func titleBtnClick(titleButton:UIButton){
        JLog(message: "")
        //titleButton.isSelected = !titleButton.isSelected
        
        //创建菜单
        let sb = UIStoryboard(name: "PopoverController", bundle: nil)
        let popoverVc = sb.instantiateInitialViewController()
        
        //设置转场代理
        popoverVc?.transitioningDelegate = popoverManager
        //设置转场样式
        popoverVc?.modalPresentationStyle = .custom
        
        //显示菜单
        present(popoverVc!, animated: true, completion: nil)
    }

    @objc private func titleBtnChange(){
        titleButton.isSelected = !titleButton.isSelected
    }
    
    @objc private func friendBtnClick(){
        JLog(message: "")
    }

    @objc private func qrcodeBtnClick(){
        let sb = UIStoryboard(name: "QRCodeViewController", bundle: nil)
        let qrcodeVc = sb.instantiateInitialViewController()
        present(qrcodeVc!, animated: true, completion: nil)
    }
    
    private func setUpHeaderView() {
        let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(downRefresh))
        header?.setTitle("下拉刷新", for: .idle)
        header?.setTitle("加载中...", for: .refreshing)
        header?.setTitle("释放更新", for: .pulling)
        tableView.mj_header = header
        tableView.mj_header.beginRefreshing()
    }
    
    private func setUpFooterView() {
        let footer = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: #selector(upRefresh))
        tableView.mj_footer = footer
    }
    
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: #selector(friendBtnClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(qrcodeBtnClick))
        //添加标题按钮
        navigationItem.titleView = titleButton
    }
    
    private func setupTipLabel(){
        navigationController?.navigationBar.insertSubview(tipLabel, at: 0)
        tipLabel.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 32)
        tipLabel.backgroundColor = UIColor.orange
        tipLabel.textColor = UIColor.white
        tipLabel.textAlignment = .center
        tipLabel.font = UIFont.systemFont(ofSize: 14)
    }
    
    private func loadstatuses(_ isNewData:Bool){
        
        //判断是否请求新数据
        var since_id = 0
        var max_id = 0
        if isNewData {
            if let mid = statusesArray.first?.mid {
                since_id = Int(mid)!
            }
        }else {
            if let mid = statusesArray.last?.mid {
                max_id = Int(mid)! - 1
            }
        }
        
        NetworkTools.shareInstance.loadHomePageInfo(since_id:"\(since_id)",max_id:"\(max_id)",access_token: (UserAccount.loadUserAccount()?.access_token)!) { (result, error) in
            
            guard let resultDict = result as? [String:AnyObject] else {
                JLog(message: error.debugDescription)
                //停止刷新
                self.tableView.mj_header.endRefreshing()
                self.tableView.mj_footer.endRefreshing()
                return
            }
            
            //获取可选类型数组
            guard let statuses = resultDict["statuses"] as? [[String:AnyObject]] else {
                return
            }
            
            var tempViewModel : [HomeViewModel] = [HomeViewModel]()
            for status in statuses {
                //字典转模型
                if !JSONSerialization.isValidJSONObject(status as Any) {
                    return
                }
                let statusData = try? JSONSerialization.data(withJSONObject: status, options: JSONSerialization.WritingOptions.prettyPrinted)
            
                let decoder = JSONDecoder()
                //处理微博创建时间日期格式
                decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in
                    let data = try decoder.singleValueContainer().decode(String.self)
                    let formatter = DateFormatter()
                    formatter.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
                    formatter.locale = Locale(identifier: "en")
                    return formatter.date(from: data)!
                })
                
                let homeViewModel = try! decoder.decode(HomeViewModel.self, from: statusData!)
                tempViewModel.append(homeViewModel)
            }
            
            //判断是下拉还是上拉
            if isNewData {
                self.statusesArray = tempViewModel + self.statusesArray
            } else {
                self.statusesArray = self.statusesArray + tempViewModel
            }
            
            //for model in self.statusesArray {
            //    JLog(message: model.mid)
            //}
            
            //缓存图片数据
            self.cachePicUrlImage(statuses: tempViewModel)
            
            //显示提示label
            self.showTipLabel(count: tempViewModel.count)
            
            //将临时数组清空
            tempViewModel = []
        }
    }
    
    private func showTipLabel(count:Int){
        tipLabel.isHidden = false
        tipLabel.text = count == 0 ? "没有新数据" : "\(count)条新数据"
        UIView.animate(withDuration: 1.0, animations: {
            self.tipLabel.frame.origin.y = 44
        }) { (_) in
            UIView.animate(withDuration: 1.0, delay: 1.5, options: [], animations: {
                self.tipLabel.frame.origin.y = 10
            }, completion: { (_) in
                self.tipLabel.isHidden = true
            })
        }
    }
    
    private func cachePicUrlImage(statuses:[HomeViewModel]){
        
        //创建group
        let group = DispatchGroup.init()
        var urls : [URL] = [URL]()
        //遍历图片url
        for status in statuses {
            for picUrls in status.pic_urls! {
                let url = URL(string:picUrls["thumbnail_pic"]!)
                urls.append(url!)
                //将异步操作放入group
                group.enter()
                SDWebImageManager.shared().loadImage(with: url, options: [], progress: nil) { (_, _, _, _, _, _) in
                    //下载完成离开group
                    group.leave()
                }
            }
        }
        
        //以上操作都完成之后刷新表格
        group.notify(queue: DispatchQueue.main) {
            //刷新表格
            self.tableView.reloadData()
            //停止刷新
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
        }
    }
}

extension HomeTableViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusesArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "HomeCellID", for: indexPath) as? HomeTableViewCell
        if cell == nil {
            cell = HomeTableViewCell(style: .default, reuseIdentifier: "HomeCellID")
        }
        //0.取出微博数据模型
        cell?.status = statusesArray[indexPath.row]
        return cell!
    }
}


